from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.settings import api_settings
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_simplejwt.exceptions import InvalidToken

from user.models import SysUser


class SysUserJWTAuthentication(JWTAuthentication):
    """
    自定义JWT认证，使用 SysUser 作为用户来源。
    解决 simplejwt 默认按 Django 内置 User 取用户导致的找不到用户问题。
    """

    def get_user(self, validated_token):
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken("Token contained no recognizable user identification")

        try:
            user = SysUser.objects.get(id=user_id)
        except SysUser.DoesNotExist:
            raise AuthenticationFailed('User not found', code='user_not_found')

        return user


